const url = require("url");
const express = require("express");
const router = express();
const bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
router.use(bodyParser.json({ limit: '50mb' }));
// router.use(bodyParser.urlencoded({extended: false, limit: '50mb'}));  
const fs = require("fs")
const path = require('path');
const os = require("os");
const multer = require("multer");
const weixin = require("../../db/weixin.js");
const {
  readDocument,
  asyncReadDocument,
  writeDocument,
  asyncWriteDocument,
  readini,
  writeini,
  deleteFile,
  asyncDeleteFile,
  createFolder,
  createFile,
  checkPath,
  isFileOrFolder,
} = require("../../db/operFile.js");
// weixin.getHttp()

// const puppeteer = require("puppeteer");

//解析form-data
function handleMultiparty(req, res, temp) {
    return new Promise((resolve, reject) => {
        // multiparty的配置 options是一个可选的配置对象 默认自动保存
        let options = {
            //设置最大文件大小
            maxFilesSize: 200 * 1024 * 1024
        };
        //设置保存路径（temp不存在是设置 options.uploadDir
        !temp ? options.uploadDir = uploadDir : null;
        // 默认自动保存
        // 创建一个Form对象
        const form = new multiparty.Form(options);

        // 监听文件上传事件（处理事件，如：修改文件名）
        form.on('file', (name, file) => {
            // console.log('file:',file)
            // 生成新的文件名（将原始文件名作为新名字，默认保存的是哈希值为文件名）
            const newFileName = uploadDir + file.originalFilename;
            // 移动文件到新的路径（原路径为设置的options.uploadDir+哈希值文件名 ）
            //注意：已存在的文件名文件会被覆盖
            fs.rename(file.path, newFileName, (error) => {
                if (error) {
                    console.error('Error:', error);
                }
            });
        });

        // 监听字段事件
        form.on('field', (name, value) => {
            // console.log('Field name:', name);
            // console.log('Field value:', value);
        });

        // 解析请求
        form.parse(req, (error, fields, files) => {
            if (error) {
                res.send({
                    code: 1,
                    reason: err
                });
                reject(error);
                return;
            }
            // console.log(fields, files)
            resolve({
                fields,
                files
            });
        });
    });
}


function getLocalIP() {
  const networkInterfaces = os.networkInterfaces();
  for (const interfaceName in networkInterfaces) {
    const addresses = networkInterfaces[interfaceName];
    for (const addressInfo of addresses) {
      // 检查是否是 IPv4 地址，且不是内部地址 (127.0.0.1)
      if (addressInfo.family === "IPv4" && !addressInfo.internal) {
        return addressInfo.address;
      }
    }
  }
  return "127.0.0.1"; // 如果没有找到，则返回本地回环地址
}
// 设置文件上传存储位置和文件名  
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './html/js/');  // 设置文件保存路径
  },
  filename: (req, file, cb) => {
    cb(null, "photo.js");  // 设置文件名为时间戳+原文件扩展名
  }
});

// 设置上传的文件大小限制
const upload = multer({ 
  storage: storage, 
  limits: { fileSize: 50 * 1024 * 1024 }  // 最大文件大小为 5MB
});
// 单文件上传：字段名为 'file'
router.post("/uploadJS", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.code(300).send("No file uploaded.");
  }
  res.send({
    code: 200,
    message: "photo.js uploaded successfully.",
  });
});
// 设置文件上传存储位置和文件名  uploadArticlePhoto
const storageArticle = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./html/js/"); // 设置文件保存路径
  },
  filename: (req, file, cb) => {
    cb(null, "articlePhoto.js"); // 设置文件名为时间戳+原文件扩展名
  },
});

// 设置上传的文件大小限制
const uploadArticle = multer({ 
  storage: storageArticle, 
  limits: { fileSize: 10 * 1024 * 1024 }  // 最大文件大小为 5MB
});
// 单文件上传：字段名为 'file'
router.post("/uploadArticlePhoto", uploadArticle.single("file"), (req, res) => {
  if (!req.file) {
    return res.code(300).send("No file uploaded.");
  }
  res.send({
    code: 200,
    message: "uploadArticlePhoto.js uploaded successfully .",
  });
});
router.post("/getScreenshot", (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  let params = req.body
  const {
    configLike,
    name,
    text,
    location,
    app,
    height,
    uiWhite,
    firstAvatar,
    appIcon,
    statusIcon,
    statusIos,
    avatarSet,
    uploadImg,
    articleEnable,
    articleTitle,
    singleHeight,
  } = params;
  console.log(
    91,
    configLike,
    name,
    text,
    location,
    app,
    height,
    uiWhite,
    firstAvatar,
    appIcon,
    statusIcon,
    statusIos,
    avatarSet,
    uploadImg,
    singleHeight,
    articleEnable,
    articleTitle
  );
  let bb = readini("./config.ini");
  if (bb.code == 200) {
    let data = bb.data
    if (configLike !== undefined) data.config.configLike = configLike;
    else data.config.configLike = 0
    if (name !== undefined) data.config.name = name;
    if (text !== undefined) data.config.text = text;
    if (location !== undefined) data.config.location = location;
    if (app !== undefined) data.config.app = app;
    else data.config.app = "";
    if (height !== undefined) data.config.height = height;
    if (uiWhite !== undefined) data.config.uiWhite = uiWhite;
    if (firstAvatar !== undefined) data.config.firstAvatar = firstAvatar;
    if (appIcon !== undefined) data.config.appIcon = appIcon;
    if (statusIcon !== undefined) data.config.statusIcon = statusIcon;
    if (avatarSet !== undefined) data.config.avatarSet = avatarSet;
    if (uploadImg !== undefined) data.config.uploadImg = uploadImg;
    else data.config.uploadImg = false;
    if (articleEnable !== undefined) data.config.articleEnable = articleEnable;
    else data.config.articleEnable = false; 
    if (articleTitle !== undefined) data.config.articleTitle = articleTitle;
    if (singleHeight !== undefined) data.config.singleHeight = singleHeight;
    else data.config.singleHeight = 0

    writeini("./config.ini",data);
  }
  const ip = getLocalIP();
  const url = `http://${ip}:3333/toBase64.html`;
  // const url = `http://127.0.0.1:3333/toBase64.html`;
  weixin.getPuppeteer(url).then((result) => {
    // console.log("图片")
    // console.log(result);
    // res.sendFile(result); // 直接发送文件
    res.json({
      image: result,
    });
  });
});
router.post("/getScreenshortPara", (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  let aa = readini("./config.ini");
  if (aa.code == 200) {
    return res.json(aa.data.config);
  }
  res.json({
    configLike: 10,
    name: "A 营销号免费广告姬123456",
    text: "很实用的教程[微笑]\n需要收集五个赞 谢谢大家啦～(　^ω^)123456",
    location: "",
    app: "",
    height: 1920,
    uiWhite: false,
    firstAvatar: false,
    appIcon: false,
    statusIcon: true,
    statusIos: false,
    avatarSet: "",
  });
});

module.exports = router